using UnityEngine;
using UI.BankingPanel.Data;
using UI.BankingPanel;
using System.Collections.Generic;

/// <summary>
/// 真正的Excel导出测试器
/// 用于测试SimpleExcelExporter的功能
/// </summary>
public class TrueExcelExportTester : MonoBehaviour
{
    [Header("测试设置")]
    [SerializeField] private bool useTestData = true;
    [SerializeField] private string customFileName = "";
    
    [Header("测试按钮")]
    [SerializeField] private UnityEngine.UI.Button testExportButton;
    [SerializeField] private UnityEngine.UI.Button clearExportsButton;
    
    [Header("状态显示")]
    [SerializeField] private UnityEngine.UI.Text statusText;
    
    private void Start()
    {
        InitializeUI();
    }
    
    /// <summary>
    /// 初始化UI
    /// </summary>
    private void InitializeUI()
    {
        // 查找测试按钮
        if (testExportButton == null)
        {
            var buttonObj = GameObject.Find("TestExportButton");
            if (buttonObj != null)
            {
                testExportButton = buttonObj.GetComponent<UnityEngine.UI.Button>();
            }
        }
        
        // 查找清理按钮
        if (clearExportsButton == null)
        {
            var buttonObj = GameObject.Find("ClearExportsButton");
            if (buttonObj != null)
            {
                clearExportsButton = buttonObj.GetComponent<UnityEngine.UI.Button>();
            }
        }
        
        // 查找状态文本
        if (statusText == null)
        {
            var textObj = GameObject.Find("StatusText");
            if (textObj != null)
            {
                statusText = textObj.GetComponent<UnityEngine.UI.Text>();
            }
        }
        
        // 绑定按钮事件
        if (testExportButton != null)
        {
            testExportButton.onClick.AddListener(TestExcelExport);
        }
        
        if (clearExportsButton != null)
        {
            clearExportsButton.onClick.AddListener(ClearExportDirectory);
        }
        
        UpdateStatus("真正的Excel导出测试器已准备就绪");
    }
    
    /// <summary>
    /// 测试Excel导出功能
    /// </summary>
    [ContextMenu("测试Excel导出")]
    public void TestExcelExport()
    {
        UpdateStatus("开始测试Excel导出...");
        
        try
        {
            BankingData testData;
            
            if (useTestData)
            {
                // 使用测试数据
                testData = CreateTestBankingData();
                UpdateStatus("使用测试数据进行导出");
            }
            else
            {
                // 尝试获取当前系统数据
                var bankingCtrl = FindObjectOfType<BankingCtrl>();
                if (bankingCtrl != null)
                {
                    testData = bankingCtrl.GetBankingData();
                    UpdateStatus("使用当前系统数据进行导出");
                }
                else
                {
                    UpdateStatus("未找到BankingCtrl，使用测试数据");
                    testData = CreateTestBankingData();
                }
            }
            
            // 执行导出（同时复制到粘贴板）
            string fileName = string.IsNullOrEmpty(customFileName) ? null : customFileName;
            var result = SimpleExcelExporter.ExportBankingDataToExcel(testData, fileName, true);
            
            if (result.Success)
            {
                UpdateStatus($"Excel导出成功！\n文件路径: {result.FilePath}");
                Debug.Log($"[TrueExcelExportTester] Excel导出成功: {result.FilePath}");
                
                // 显示文件信息
                if (System.IO.File.Exists(result.FilePath))
                {
                    var fileInfo = new System.IO.FileInfo(result.FilePath);
                    UpdateStatus($"Excel导出成功！\n文件大小: {fileInfo.Length} 字节\n文件路径: {result.FilePath}");
                }
            }
            else
            {
                UpdateStatus($"❌ Excel导出失败: {result.Message}");
                Debug.LogError($"[TrueExcelExportTester] Excel导出失败: {result.Message}");
            }
        }
        catch (System.Exception ex)
        {
            UpdateStatus($"❌ 导出过程中发生错误: {ex.Message}");
            Debug.LogError($"[TrueExcelExportTester] 导出错误: {ex.Message}\n{ex.StackTrace}");
        }
    }
    
    /// <summary>
    /// 清理导出目录
    /// </summary>
    [ContextMenu("清理导出目录")]
    public void ClearExportDirectory()
    {
        try
        {
            string exportDir = System.IO.Path.Combine(Application.persistentDataPath, "Exports");
            
            if (System.IO.Directory.Exists(exportDir))
            {
                var files = System.IO.Directory.GetFiles(exportDir, "*.xlsx");
                int deletedCount = 0;
                
                foreach (var file in files)
                {
                    System.IO.File.Delete(file);
                    deletedCount++;
                }
                
                UpdateStatus($"✅ 已清理 {deletedCount} 个Excel文件");
                Debug.Log($"[TrueExcelExportTester] 已清理 {deletedCount} 个Excel文件");
            }
            else
            {
                UpdateStatus("导出目录不存在，无需清理");
            }
        }
        catch (System.Exception ex)
        {
            UpdateStatus($"❌ 清理失败: {ex.Message}");
            Debug.LogError($"[TrueExcelExportTester] 清理失败: {ex.Message}");
        }
    }
    
    /// <summary>
    /// 创建测试用的银行数据
    /// </summary>
    private BankingData CreateTestBankingData()
    {
        var bankingData = new BankingData();
        bankingData.odds = 42.0f;
        
        // 创建测试数据，按照用户要求的格式，展示相同金额分组功能
        var testNumbers = new Dictionary<int, (float total, float eat, float report)>
        {
            // 总数据：01,02,03各100；05,06,08各50
            // 自己吃码：01,02,03各50；05,06,08各25  
            // 上报数据：01,02,03各50；05,06,08各25
            {1, (100f, 50f, 50f)},
            {2, (100f, 50f, 50f)},
            {3, (100f, 50f, 50f)},
            {5, (50f, 25f, 25f)},
            {6, (50f, 25f, 25f)},
            {8, (50f, 25f, 25f)},
            
            // 添加更多相同金额的测试数据来展示分组功能
            {10, (200f, 100f, 100f)},
            {11, (200f, 100f, 100f)}, // 与10号相同金额
            {15, (75f, 30f, 45f)},
            {16, (75f, 30f, 45f)},    // 与15号相同金额
            {20, (150f, 80f, 70f)},
            {25, (90f, 40f, 50f)},
            {26, (90f, 40f, 50f)},    // 与25号相同金额
            {27, (90f, 40f, 50f)},    // 与25,26号相同金额
            {30, (120f, 60f, 60f)},
            {35, (80f, 35f, 45f)},
            {36, (80f, 35f, 45f)},    // 与35号相同金额
            {40, (110f, 55f, 55f)},
            {45, (95f, 45f, 50f)},
            {46, (95f, 45f, 50f)}     // 与45号相同金额
        };
        
        // 初始化所有号码数据
        var allNumberData = new List<NumberBetData>();
        for (int i = 1; i <= 49; i++)
        {
            var numberData = new NumberBetData(i)
            {
                totalBetAmount = 0f,
                selfBetAmount = 0f,
                reportAmount = 0f,
                riskValue = 0f
            };
            
            // 如果是测试号码，设置相应的值
            if (testNumbers.ContainsKey(i))
            {
                var testData = testNumbers[i];
                numberData.totalBetAmount = testData.total;
                numberData.selfBetAmount = testData.eat;
                numberData.reportAmount = testData.report;
                numberData.riskValue = testData.total * bankingData.odds - testData.total;
            }
            
            allNumberData.Add(numberData);
        }
        
        // 设置数据到BankingData
        // 注意：这里需要根据实际的BankingData结构来设置数据
        // 如果BankingData有SetAllNumberBetData方法，使用它
        // 否则需要通过其他方式设置数据
        
        Debug.Log($"[TrueExcelExportTester] 创建了包含 {testNumbers.Count} 个有效号码的测试数据");
        
        return bankingData;
    }
    
    /// <summary>
    /// 更新状态显示
    /// </summary>
    private void UpdateStatus(string message)
    {
        if (statusText != null)
        {
            statusText.text = $"[{System.DateTime.Now:HH:mm:ss}] {message}";
        }
        
        Debug.Log($"[TrueExcelExportTester] {message}");
    }
    
    /// <summary>
    /// 获取导出目录信息
    /// </summary>
    [ContextMenu("查看导出目录信息")]
    public void ShowExportDirectoryInfo()
    {
        try
        {
            string exportDir = System.IO.Path.Combine(Application.persistentDataPath, "Exports");
            
            if (System.IO.Directory.Exists(exportDir))
            {
                var files = System.IO.Directory.GetFiles(exportDir, "*.xlsx");
                var csvFiles = System.IO.Directory.GetFiles(exportDir, "*.csv");
                
                string info = $"导出目录: {exportDir}\n";
                info += $"Excel文件数量: {files.Length}\n";
                info += $"CSV文件数量: {csvFiles.Length}\n";
                
                if (files.Length > 0)
                {
                    info += "Excel文件列表:\n";
                    foreach (var file in files)
                    {
                        var fileInfo = new System.IO.FileInfo(file);
                        info += $"- {System.IO.Path.GetFileName(file)} ({fileInfo.Length} 字节)\n";
                    }
                }
                
                UpdateStatus(info);
            }
            else
            {
                UpdateStatus("导出目录不存在");
            }
        }
        catch (System.Exception ex)
        {
            UpdateStatus($"❌ 获取目录信息失败: {ex.Message}");
        }
    }
    
    private void OnDestroy()
    {
        // 清理事件监听
        if (testExportButton != null)
        {
            testExportButton.onClick.RemoveListener(TestExcelExport);
        }
        
        if (clearExportsButton != null)
        {
            clearExportsButton.onClick.RemoveListener(ClearExportDirectory);
        }
    }
} 